package cn.com.shaom.learning.sb.mq.jms.example2;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.annotation.EnableJms;
import org.springframework.jms.support.converter.MappingJackson2MessageConverter;
import org.springframework.jms.support.converter.MessageConversionException;
import org.springframework.jms.support.converter.MessageConverter;
import org.springframework.jms.support.converter.MessageType;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.TextMessage;

/**
 * ClassName: JmsConfig
 * Description:
 * Date: 2017/12/29 10:11 【需求编号】
 *
 * @author Shaom
 * @version V1.0.0
 */
@EnableJms
@Configuration
public class JmsConfig {

    /**
     * Serialize message content to json using TextMessage
     * 使用自定义的 MessageConverter 处理，也可以可以使用FastJson自己写一个
     *
     * @return
     */
    @Bean
    public MessageConverter jacksonJmsMessageConverter() {
        MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
        converter.setTargetType(MessageType.TEXT);
        converter.setTypeIdPropertyName("_type");
        return converter;

//        return new JsonMessageConverter();
    }

    /**
     * 自定义简单实现
     */
    class JsonMessageConverter implements MessageConverter {




        @Override
        public Message toMessage(Object object, Session session) throws JMSException, MessageConversionException {
            //这边默认是TextMessage
            return session.createTextMessage(JSON.toJSONString(object));
        }

        @Override
        public Object fromMessage(Message message) throws JMSException, MessageConversionException {
            //这边默认是TextMessage
            TextMessage msg = (TextMessage) message;
            return msg.getText();
        }
    }

}
